var modifyOrAddFlag;
var oldValue = {};
$(document)
		.ready(
				function() {

					// 存放选中的调度的领域接口的URL
					window.systemInterfaceUrl = null;
					// 存放选中的调度的运行状态
					window.runStatus = null;

					// 所属领域下拉框
					$('#comboxSearchfieldName')
							.combobox(
									{
										url : BASE_URL_FIELD_SEARCH
												+ '/findAllOfCurrentUserCanManage'
												+ '?v=' + Math.random(),
										valueField : 'id',
										textField : 'name',
										editable : false,
										method : 'get',
										loadFilter : function(data) {
											var allCheck = {
												'id' : '',
												'name' : '全部'
											};
											data.content.unshift(allCheck);
											return data.content;
										},
										onSelect : function(record) {
											comboxSearchSystemName
													.combobox(
															{
																disabled : false,
																method : 'get',
																queryParams : {
																	fieldId : record.id
																},
																url : BASE_URL_FIELD_SYSTEM_SEARCH
																		+ '/findByFieldOfCurrentUserCanManage'
																		+ '?v='
																		+ Math
																				.random(),
																valueField : 'id',
																textField : 'name',
																data : '',
																loadFilter : function(
																		data) {
																	var allCheck = {
																		'id' : '',
																		'name' : '全部'
																	};
																	data.content
																			.unshift(allCheck);
																	return data.content;
																},
																onLoadSuccess : function() {
																	comboxSearchSystemName
																			.combobox(
																					'setValue',
																					'');
																}
															}).load();
										},
										onLoadSuccess : function() {
											$('#comboxSearchfieldName')
													.combobox('setValue', '');
										}
									});

					// 所属系统下拉框
					var comboxSearchSystemName = $('#comboxSearchSystemName')
							.combobox({
								disabled : true,
								valueField : 'id',
								textField : 'name',
								editable : false,
								data : [ {
									id : '',
									name : '全部',
									'selected' : 'true'
								} ]
							});

					$('#comboxFieldName')
							.combobox(
									{
										url : BASE_URL_FIELD_SEARCH
												+ '/findAllOfCurrentUserCanManage'
												+ '?v=' + Math.random(),
										valueField : 'id',
										textField : 'name',
										editable : false,
										method : 'get',
										loadFilter : function(data) {
											var allCheck = {
												'id' : '',
												'name' : '请选择'
											};
											if (data.content) {
												data.content.unshift(allCheck);
											} else {
												return data;
											}
											return data.content;
										},
										onSelect : function(record) {
											comboxSystemName
													.combobox(
															{
																disabled : false,
																method : 'get',
																queryParams : {
																	fieldId : record.id
																},
																url : BASE_URL_FIELD_SYSTEM_SEARCH
																		+ '/findByFieldOfCurrentUserCanManage'
																		+ '?v='
																		+ Math
																				.random(),
																valueField : 'id',
																textField : 'name',
																data : '',
																loadFilter : function(
																		data) {

																	var allCheck = {
																		'id' : '',
																		'name' : '请选择'
																	};
																	data.content
																			.unshift(allCheck);
																	return data.content;
																},
																onSelect : function(
																		record) {
																	comboxInterface
																			.combobox({
																				disabled : false,
																				method : 'get',
																				queryParams : {
																					fieldSystemId : record.id
																				},
																				url : BASE_URL_SYSTEM_INTERFACE_SEARCH
																						+ '/findByOwnerFieldSystem_Id'
																						+ '?v='
																						+ Math
																								.random(),
																				valueField : 'id',
																				textField : 'jobName',
																				data : '',
																				loadFilter : function(
																						data) {
																					if (data[0].id == "") {
																						return data;
																					}
																					var allCheck = {
																						'id' : '',
																						'jobName' : '请选择'
																					};
																					data
																							.unshift(allCheck);
																					return data;

																				},
																				onLoadSuccess : function() {
																					$(
																							'#comboxInterface')
																							.combobox(
																									'setValue',
																									'');
																				}
																			});
																},
																onLoadSuccess : function() {
																	$(
																			'#comboxInterface')
																			.combobox(
																					'setValue',
																					'');

																}
															}).load();
											comboxInterface.combobox({
												disabled : true,
												valueField : 'id',
												textField : 'jobName',
												editable : false,
												url : '',
												data : [],
												loadFilter : function(data) {
													var allCheck = {
														id : '',
														jobName : '请选择',
														'selected' : 'true'
													};
													data.unshift(allCheck);
													return data;
												}
											});
										}

									});

					var comboxSystemName = $('#comboxSystemName').combobox({
						disabled : true,
						valueField : 'id',
						textField : 'name',
						editable : false,
						url : '',
						data : [],
						loadFilter : function(data) {
							var allCheck = {
								id : '',
								name : '请选择',
								'selected' : 'true'
							};
							data.unshift(allCheck);
							return data;
						}

					});

					// 所属系统下的所有接口
					var comboxInterface = $('#comboxInterface').combobox({
						disabled : true,
						valueField : 'id',
						textField : 'jobName',
						editable : false,
						url : '',
						data : [],
						loadFilter : function(data) {
							var allCheck = {
								id : '',
								jobName : '请选择',
								'selected' : 'true'
							};
							data.unshift(allCheck);
							return data;
						}
					})

					$('#comboxExecutionCycleTime')
							.combobox(
									{
										url : BASE_URL_DATA_DICTIONARY_VALUE_SEARCH
												+ '/findByTypeCode?typeCode='
												+ DDTC_KETTLE_JOB_SCHEDULE_CYCLE_UNIT
												+ '&v=' + Math.random(),
										valueField : 'valueCode',
										textField : 'valueName',
										editable : false,
										method : 'get',
										loadFilter : function(data) {
											return data;
										},
										onChange : function(e) {
											var chooseVal = $(
													"#comboxExecutionCycleTime")
													.combobox('getValue');
											var cycleNum = $(
													'#txtExecutionCycleNumber')
													.val();
											if (chooseVal == "5"
													&& cycleNum == "1") {
												$(
														".daySel, .txtEvery, .text_tips, #end_time_li")
														.show();
											} else if (chooseVal == "1") {
												$(
														".txtEvery, .daySel, .text_tips, #end_time_li")
														.hide();
											} else {
												$(
														".txtEvery, .text_tips, #end_time_li")
														.show();
												$(".daySel").hide();
											}
										}

									});

					$("#datagrid")
							.datagrid(
									{
										url : BASE_URL_API
												+ '/ifResTime/search/findIfResTimeInfo?v='
												+ Math.random(),
										method : 'get',
										autoRowHeight : true,
										singleSelect : true,
										striped : true,
										nowrap : false,
										pageSize : 20,
										pageList : [ 10, 20, 50, 100 ],
										columns : [ [

												{
													field : 'fieldName',
													title : '所属领域',
													width : 40
												},
												{
													field : 'systemName',
													title : '所属系统',
													width : 40
												},
												{
													field : 'ifName',
													title : '接口名称',
													width : 60,
													align : 'center'
												},
												{
													field : 'period',
													title : '周期',
													width : 10,
													align : 'center',
													formatter : function(value,
															rowData, rowIndex) {
														return value == '1' ? "昨天"
																: (value=='2'?'今天':'7天内');
													}
												},
												{
													field : 'esbAvg',
													title : '引擎平均响应时间(秒)',
													width : 35
												},
												{
													field : 'esbMax',
													title : '引擎最大响应时间(秒)',
													width : 35
												},
												{
													field : 'avg',
													title : '平均响应时间(秒)',
													width : 30
												},
												{
													field : 'max',
													title : '最大响应时间(秒)',
													width : 30
												} ] ],
										pagination : true,
										onSelect : function(rowIndex, rowData) {
										},
										onUnselect : function() {
										},
										loadFilter : function(data) {
											// alert("inData:"+JSON.stringify(data));
											return {
												total : data.totalElements,
												rows : data.content
											};
										},
										onBeforeLoad : function(param) {
											param.page -= 1;
											param.size = param.rows;
											delete param.rows;

											var fieldId = $(
													'#comboxSearchfieldName')
													.combobox('getValue');
											if (fieldId != "") {
												param.fieldId = fieldId;
											}

											var systemId = $(
													'#comboxSearchSystemName')
													.combobox('getValue');
											if (systemId != "") {
												param.systemId = systemId;
											}

											var ifName = $(
													'#txtSearchInterfaceName')
													.val();
											if (ifName != "") {
												param.ifName = ifName;
											}
											param.period=$("input[name='chboxPeriod']:checked").val();
										},
										onBeforeEdit : function(index, row) {
											row.editing = true;
											// $('#datagrid').datagrid(
											// 'refreshRow', index);
											oldValue[row.quantityId] = {
												requestThreshold : row.requestThreshold,
												requestMax : row.requestMax
											};
											// alert(JSON.stringify(oldValue));
										},
										onAfterEdit : function(index, row) {
											row.editing = false;
											$("#datagrid").datagrid(
													"acceptChanges");
											$('#datagrid').datagrid(
													'refreshRow', index);
										},
										onCancelEdit : function(index, row) {
											row.editing = false;
											$('#datagrid').datagrid(
													'refreshRow', index);
										},
							            onLoadSuccess: function (data) {
							                if (data.rows.length > 0) {
							                    // 调用mergeCellsByField()合并单元格
							                    mergeCellsByField("datagrid", "fieldName,systemName,ifName");
							                }
							            }
									});

					$("#datagrid").datagrid('getPager').pagination({
						displayMsg : '当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
					});
					$(".panel-tool-close, #instance_cancel").click(function(e) {
						$("body").css("overflow-x", "inherit")
					});

				});
/**
 * EasyUI DataGrid根据字段动态合并单元格 参数 tableID 要合并table的id 参数 colList
 * 要合并的列,用逗号分隔(例如："name,department,office");
 */
function mergeCellsByField(tableID, colList) {
    var ColArray = colList.split(",");
    var tTable = $("#" + tableID);
    var TableRowCnts = tTable.datagrid("getRows").length;
    var tmpA;
    var tmpB;
    var PerTxt = "";
    var CurTxt = "";
    var alertStr = "";
    for (j = ColArray.length - 1; j >= 0; j--) {
        PerTxt = "";
        tmpA = 1;
        tmpB = 0;

        for (i = 0; i <= TableRowCnts; i++) {
            if (i == TableRowCnts) {
                CurTxt = "";
            }
            else {
                CurTxt = tTable.datagrid("getRows")[i][ColArray[j]];
            }
            if (PerTxt == CurTxt) {
                tmpA += 1;
            }
            else {
                tmpB += tmpA;
                
                tTable.datagrid("mergeCells", {
                    index: i - tmpA,
                    field: ColArray[j],　　// 合并字段
                    rowspan: tmpA,
                    colspan: null
                });
                tTable.datagrid("mergeCells", { // 根据ColArray[j]进行合并
                    index: i - tmpA,
                    field: "Ideparture",
                    rowspan: tmpA,
                    colspan: null
                });
               
                tmpA = 1;
            }
            PerTxt = CurTxt;
        }
    }
}
function edit(rowIndex, element) {
	var parent = element.closest('.edit_div');
	var save = parent.find('.save');
	var cancel = parent.find('.cancel');
	element.hide();
	save.show();
	cancel.show();
	$("#datagrid").datagrid("beginEdit", rowIndex);
}
function cancel(rowIndex, element) {
	var parent = element.closest('.edit_div');
	var edit = parent.find('.edit');
	var save = parent.find('.save');
	element.hide();
	save.hide();
	edit.show();
	$("#datagrid").datagrid("endEdit", rowIndex);
	// 还原行数据
	var row = $('#datagrid').datagrid('getData').rows[rowIndex];
	row.requestThreshold = oldValue[row.quantityId].requestThreshold;
	row.requestMax = oldValue[row.quantityId].requestMax;
	$('#datagrid').datagrid('refreshRow', rowIndex);
}

function save(rowIndex, element) {
	var parent = element.closest('.edit_div');
	var edit = parent.find('.edit');
	var cancel = parent.find('.cancel');
	element.hide();
	cancel.hide();
	edit.show();
	$("#datagrid").datagrid("endEdit", rowIndex);
	var result = false;
	var row = $('#datagrid').datagrid('getData').rows[rowIndex];
	var id = row.quantityId;
	var requestThreshold = row.requestThreshold;
	var requestMax = row.requestMax;
	var data = '{"id":"' + id + '","requestThreshold":"' + requestThreshold
			+ '" ,' + '"requestMax":"' + requestMax + '"}';
	$.ajax({
		type : "post",
		url : BASE_URL_API + '/flowControl/updateRequestQuantity' + '?v='
				+ Math.random(),
		dataType : 'json',
		data : data,
		contentType : "application/json",
		success : function(data) {
			if (data.result == true) {
				result = true;
				$.messager.alert('提示', "<p>编辑成功！</p>", 'info', function() {
					refresh();
				});
			} else {
				$.messager.alert('错误', "<p>" + data.msg + "</p>", "error",
						function() {
							refresh();
						});
			}
		},
		error : function() {
			$.messager.alert('错误', '<p>服务异常，服务测试失败，请稍后重试或联系管理员!</p>', 'error',
					function() {
						refresh();
					});
		}
	});
	return result;
}
// 还原行数据
function reset(rowIndex) {
	var row = $('#datagrid').datagrid('getData').rows[rowIndex];
	row.requestThreshold = oldValue[row.quantityId].requestThreshold;
	row.requestMax = oldValue[row.quantityId].requestMax;
	$('#datagrid').datagrid('refreshRow', rowIndex);
}
// 查询
function search() {
	oldValue = {};
	$('#datagrid').datagrid('reload');
}
function refresh() {
	oldValue = {};
	$('#datagrid').datagrid('reload');
}
